import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
	// 主页
	{
		path: '/',
		name: 'Home',
		// 动态引入组件。相当于: 
		// import Home from '../views/Home.vue' (引入 Home 组件)
		// component: Home (配置 Home 组件的路由)
		// @ 表示 src 根目录
		component: () => import('@/views/Home'),
	},
	// 注册
	{
		path: '/register',
		name: 'register',
		component: () => import('@/views/auth/Register'),
		// 定义网页的标题
		meta: { title: '注册' },
	},
	// 登录
	{
		name: 'login',
		path: '/login',
		component: () => import('@/views/auth/Login'),
		meta: { title: '登录' },
	},
	// 发布
	{
		name: 'post-create',
		path: '/post/create',
		component: () => import('@/views/post/Create'),
		meta: { title: '信息发布', requireAuth: true },
	},
	// 编辑
	{
		name: 'post-edit',
		path: '/post/edit/:postId',
		component: () => import('@/views/post/Edit'),
		meta: { title: '编辑', requireAuth: true }
	},
	// 详情
	{
		name: 'post-detail',
		path: '/post/:postId',
		component: () => import('@/views/post/Detail'),
		meta: { title: '详情' },
	},
	// 标签
	{
		name: 'tag',
		path: '/tag/:tagName',
		component: () => import('@/views/tag/Tag'),
		meta: { title: '主题列表' }
	},
	// 检索
	{
		name: 'search',
		path: '/search',
		component: () => import('@/views/Search'),
		meta: { title: '检索' }
	},
	// 用户主页
	{
		name: 'user',
		path: '/member/:username/home',
		component: () => import('@/views/user/Profile'),
		meta: { title: '用户主页' }
	},
	// 用户设置
	{
		name: 'user-setting',
		path: '/member/:username/setting',
		component: () => import('@/views/user/Setting'),
		// 登录才可以访问 加上 requireAuth
		// 只有登录才能跳转到该路由页面
		meta: { title: '设置', requireAuth: true }
	},
	// 若非以上任何路由中的一个，则路由到 404 页面
	{
		path: '*',
		redirect: '/404',
		// hidden: 表示当前是隐藏路由
		hidden: true,
	},
	// 404 页面 
	{
		path: '/404',
		name: '404',
		component: () => import('@/views/error/404'),
		meta: { title: '404-NotFound' },
	}
]

// 重写 Vue router 的 push 功能
// 当通过 router.push 强制通过 Vue Router 跳转时，捕捉异常而不是抛出异常
// NavigationDuplicated: Avoided redundant navigation to current location: '/'
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  	return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  	routes,
})

export default router
